package com.drd.dt.exception;

import com.drd.dt.util.ResultUtil;
import com.drd.dt.common.tips.Tip;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author th
 * Created by cdyoue on 2019/11/04.
 */
@RestControllerAdvice
public class BussinessExceptionHandle extends BaseControllerExceptionHandler {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public Tip handle(Exception e, HttpServletRequest request, HttpServletResponse response) {
        if (e instanceof MethodArgumentNotValidException){
            MethodArgumentNotValidException c = (MethodArgumentNotValidException) e;
            List<ObjectError> errors =c.getBindingResult().getAllErrors();
            return ResultUtil.result(HttpStatus.NOT_ACCEPTABLE.value(),errors.get(0).getDefaultMessage());
        }
        if (e instanceof BussinessException){
            BussinessException exception = (BussinessException)e;
            logger.error(exception.getMessage() + "{}",exception);
            return ResultUtil.result(exception.getCode(),exception.getMessage());
        }
        logger.error("未知错误: {}",e);
        return ResultUtil.result(500, e.getMessage());
    }
}
